<template>
  <div class="view-fill">
    <div v-if="!modifyInfo.visible" class="app-container-flex">
      <NewFullScreen
        v-model="showDialog"
        :title="title"
        :btn-list="fullInfo.btnList"
        :needOperateAffair="true"
        :operateAffairData="affairTableInfo"
        @returnBack="returnBack"
      >
        <template v-slot:full-button>
          <PopoverPrint
            ref="popoverShow"
            v-model:popoverVisible="popoverVisible"
            :canPrint="true"
            :templateArr="templateArr"
            @tempClick="tempClick"
            @print="print"
          ></PopoverPrint>
          <el-button
            v-if="
              $permission('useStoreApplication:revoke') &&
              infoList.data.status === 3 &&
              infoList.data.storeDepotIsCargoSpaceManage != 1
            "
            @click="revoke"
            >领用退回</el-button
          >
          <el-button
            v-if="
              $permission('useStoreApplication:store') &&
              infoList.data.status === 1
            "
            @click="storage"
            >入库</el-button
          >
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <BasicInformation
              :info="infoList"
              :label-width="infoList.labelWidth"
            >
            </BasicInformation>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="$t('detailInfo')" />
          </div>
          <div class="model-panel-body">
            <PageFilter
              v-model:query="filterInfo.query"
              :filter-list="filterInfo.list"
            ></PageFilter>
            <div class="flex_full_item">
              <div class="flex_full_item">
                <!-- 表格 -->
                <PageTable
                  :refresh="tableInfo.refresh"
                  :init-curpage="tableInfo.initCurpage"
                  v-model:data="tableInfo.data"
                  :pager="false"
                  :summary="true"
                  :check-box="false"
                  :tab-index="true"
                  :summary-field-list="tableInfo.summaryFieldList"
                  :field-list="tableInfo.fieldList"
                  :handle="tableInfo.handle"
                  :isDynamic="true"
                >
                </PageTable>
              </div>
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <individual-details
      v-if="individualInfo.visible"
      v-model:show-dialog="individualInfo.visible"
      v-model:query="individualInfo.query"
      :info="individualInfo.info"
    />
    <use-application-modify
      v-if="modifyInfo.visible"
      :orderId="''"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      fromType="useStore"
      saveFrom="useStore"
      :storeOrderId="modifyInfo.id"
      :storeOrderNo="modifyInfo.orderNo"
      :useReturnImportStore="''"
      @returnModify="returnModify"
    />
  </div>
</template>

<script setup name="useExportDetails">
import {
  detailUseExport,
  getUseExportDetailExtAll,
  inBound,
  exportUseStoreApplication,
  validateRevoke,
} from '@/api/use.js'
import UseApplicationModify from '@/views/useReturn/application/modify'
import { orderAffairAll } from '../../../api/affair'
import IndividualDetails from './IndividualDetails'
import { getCustomizeSetting } from '@/api/customize'
import { ElMessageBox } from 'element-plus'
import { doPrint } from '@/utils/exportUtil.js'
import { selectByCodeAndDept } from '@/api/report.js'
import { updatePrintCount } from '@/api/mapping'
const { proxy } = getCurrentInstance()
const props = defineProps(['visible', 'id', 'orderNo'])
const title = ref('入库单详情')
const infoList = ref({
  data: {},
  fieldList: [
    { label: '出库单号', value: 'orderNo', type: 'text' },
    { label: '领用申请单号', value: 'applicationOrderNo', type: 'text' },
    { label: '状态', value: 'statusValue', type: 'text' },
    { label: '领用人', value: 'applicationUserName', type: 'text' },
    { label: '领用部门', value: 'storeDeptName', type: 'text' },
    { label: '领入仓库', value: 'storeDepotName', type: 'text' },
    { label: '领出仓库', value: 'exportDepotName', type: 'text' },
    { label: '领用日期', value: 'applicationTime', type: 'text' },
    { label: '创建人', value: 'createUserName', type: 'text' },
    { label: '创建时间', value: 'createTime', type: 'text' },
    { label: '更新人', value: 'updateUserName', type: 'text' },
    { label: '更新时间', value: 'updateTime', type: 'text' },
    {
      label: '是否寄售业务',
      value: 'isConsignBusinessValue',
      type: 'text',
      show: proxy.$store.state.permission.systemConfig.is_consign_business == 1,
    },
    {
      label: '业务日期',
      value: 'businessDate',
      type: 'text',
    },
    { label: '备注', value: 'remark', type: 'text', type: 'popover' },
  ],
  labelWidth: '130px',
})
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '80',
    btList: [
      {
        label: '个体详情',
        event: showDetail,
        show: true,
      },
    ],
  },
})
const filterInfo = ref({
  query: {
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.id,
      },
      acquisitionReplaceConsume: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
    },
    queryParams: {},
    customizeUserVO: {},
  },
  list: [
    {
      label: '类型',
      value: 'acquisitionReplaceConsume',
      type: 'select-model',
      checkDefault: true,
      clearable: false,
      code: 'acquisition_replace_consume',
      event: changeType,
    },
  ],
})
const fullInfo = ref({
  btnList: [
    {
      label: '导出excel',
      event: exportExcel,
      show: proxy.$permission('useStoreApplication:exportExcel'),
    },
  ],
})
const affairTableInfo = ref({
  api: orderAffairAll,
  query: {
    orderType: 20,
    orderNo: props.orderNo,
    sort: 'operate_time desc',
  },
})
const individualInfo = ref({
  visible: false,
  query: {},
  info: {},
})
const modifyInfo = ref({
  visible: false,
  title: '领用退回',
  id: '',
  orderNo: '',
})
const showDialog = computed({
  get() {
    return props.visible
  },
  set(val) {
    proxy.$emit('update:visible', val) // 更新父组件visible
  },
})
watch(
  () => props.visible,
  (val) => {
    showDialog.value = val
  },
  { immediate: true }
)
function revoke() {
  //撤回
  //校验库存产品是否充足
  validateRevoke(infoList.value.data.id).then((resp) => {
    if (resp && resp.success) {
      modifyInfo.value.visible = true
      modifyInfo.value.id = infoList.value.data.id
      modifyInfo.value.orderNo = infoList.value.data.orderNo
    }
  })
}
function returnBack() {
  proxy.$emit('returnBack', false)
}
function getList() {
  getUseExportDetailExtAll(filterInfo.value.query).then((res) => {
    if (res && res.success) {
      tableInfo.value.data = res.data
    }
  })
}
function setBtnStatus() {
  if (fullInfo.value.btnList[1]) {
    if (proxy.$permission('useStoreApplication:print')) {
      fullInfo.value.btnList[1].show = true
    } else {
      fullInfo.value.btnList[1].show = false
    }
  }
}
function changeType(val) {
  if (val == '1') {
    filterInfo.value.query.queryMap.acquisitionReplaceConsume.value = 1
  } else if (val == '0') {
    filterInfo.value.query.queryMap.acquisitionReplaceConsume.value = null
  }
  getList()
}
//行入库
function storage() {
  ElMessageBox.confirm('此操作将更新数据, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      let param = []
      param.push(infoList.value.data.id)

      inBound(param).then((res) => {
        if (res.success) {
          getMain()
        }
      })
    })
    .catch((e) => {})
}

//个体详情
function showDetail(row) {
  let ids
  if (row.groupConcatIds) {
    //未定义表示没有分组条件
    ids = row.groupConcatIds
  } else {
    ids = '' + row.id
  }
  individualInfo.value.query = {
    id: {
      queryType: 'IN',
      queryCategory: 'AND',
      value: ids,
    },
    orderId: {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: props.id,
    },
  }
  individualInfo.value.info = row
  individualInfo.value.visible = true
}
//导出excel
function exportExcel() {
  exportUseStoreApplication(filterInfo.value.query).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}

const templateArr = ref([])
const popoverVisible = ref(false)
//打印
function print() {
  selectByCodeAndDept({
    tempCode: 'useStorageDetail',
    deptId: infoList.value.data.deptId,
  }).then((res) => {
    if (res && res.success) {
      templateArr.value = res.data
      popoverVisible.value = true
      // 一条数据则直接打印
      if (templateArr.value.length === 1) {
        proxy.$refs.popoverShow.hidePopover()
        doPrint({
          name: templateArr.value[0].ureportName,
          params: {
            applicationId: infoList.value.data.id,
            orderId: infoList.value.data.id,
            orderNo: infoList.value.data.orderNo,
          },
          callback: printCallback,
          printCount: true,
          data: {},
        })
      }
    }
  })
}
function tempClick(item) {
  doPrint({
    name: item.ureportName,
    params: {
      applicationId: infoList.value.data.id,
      orderId: infoList.value.data.id,
      orderNo: infoList.value.data.orderNo,
    },
    callback: printCallback,
    printCount: true,
    data: {},
  })
  popoverVisible.value = false
}
function printCallback() {
  try {
    // 打印成功增加打印次数
    updatePrintCount({
      orderNo: infoList.value.data.orderNo,
      tempCode: 'useStorageDetail',
      orderId: props.id,
      orderType: 20,
    })
  } catch (error) {}
}
function getMain() {
  detailUseExport(props.id).then((resp) => {
    if (resp && resp.success) {
      infoList.value.data = resp.data
      getList()
      setBtnStatus(resp.data)
    }
  })
}
function getCustomize() {
  let param = {
    tableKey:
      'useExportOrderInDetail-com.slip.spd.entity.vo.use.UseExportOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = res.data
      tableInfo.value.fieldList = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail
      )
      getMain()
    }
  })
}

let obj = {
  orderNo: {
    label: '单号',
    value: 'orderNo',
    componentType: 'input',
    show: false,
    // type: 'slot',
    hidden: true,
  },
  price: {
    label: '单价',
    value: 'price',
    minWidth: '150px',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('useStoreApplication:price'),
    hidden: true,
  },
  sumAmount: {
    label: '总金额',
    value: 'sumAmount',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('useStoreApplication:price'),
    hidden: true,
  },
  defaultSupplierPrice: {
    label: '默认供应商价格',
    value: 'defaultSupplierPrice',
    type: 'column',
    componentType: 'price',
    permission: !proxy.$permission('useStoreApplication:price'),
    formatter: proxy.$fn.TripartiteMethod,
    hidden: true,
    show: false,
  },
  availableQty: {
    label: '可出库数量',
    value: 'availableQty',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    hidden: true,
  },
}
tableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
getCustomize()
</script>

<style scoped></style>
